import { 
  Controller, 
  Post, 
  Get, 
  Put,
  Delete,
  Body, 
  Param,
  Query,
  Headers,
  Req,
  Logger,
  BadRequestException
} from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { Request } from 'express';
import { EnhancedForwardingService } from '../services/enhanced-forwarding.service';
import { AdapterRegistryService } from '../core/adapter-registry.service';
import { ApiProvider, TargetProvider } from '../interfaces/api-adapter.interface';
import { MessagesQueryDto, AnthropicExtendedHeaders } from '../dto/messages.dto';

/**
 * 通用代理控制器
 * 支持动态路由到不同的 AI API
 * 每个 AI API 保持其完整的接口结构
 */
@ApiTags('Universal AI API Proxy')
@Controller('proxy')
export class UniversalProxyController {
  private readonly logger = new Logger(UniversalProxyController.name);

  constructor(
    private readonly enhancedForwarding: EnhancedForwardingService,
    private readonly adapterRegistry: AdapterRegistryService
  ) {}

  /**
   * Anthropic API 代理 - 完整接口保持
   * /proxy/anthropic/v1/messages
   * /proxy/anthropic/v1/models
   * /proxy/anthropic/v1/messages/count-tokens
   */
  @Post('anthropic/v1/messages')
  @ApiOperation({ summary: 'Anthropic Messages API' })
  async anthropicMessages(
    @Body() request: any, 
    @Query() query: MessagesQueryDto,
    @Headers() headers: AnthropicExtendedHeaders, 
    @Req() req: Request
  ) {
    // TODO: Process beta query parameters in universal proxy
    // TODO: Handle anthropic-beta and X-Stainless-* headers
    return this.forwardRequest(ApiProvider.ANTHROPIC, 'messages', request, headers, req, query);
  }

  @Post('anthropic/v1/messages/count-tokens')
  @ApiOperation({ summary: 'Anthropic Count Tokens API' })
  async anthropicCountTokens(
    @Body() request: any, 
    @Query() query: MessagesQueryDto,
    @Headers() headers: AnthropicExtendedHeaders, 
    @Req() req: Request
  ) {
    // TODO: Process beta parameters for count-tokens in universal proxy
    return this.forwardRequest(ApiProvider.ANTHROPIC, 'count-tokens', request, headers, req, query);
  }

  @Get('anthropic/v1/models')
  @ApiOperation({ summary: 'Anthropic Models API' })
  async anthropicModels(@Headers() headers: any, @Req() req: Request) {
    return this.forwardRequest(ApiProvider.ANTHROPIC, 'models', {}, headers, req);
  }

  /**
   * OpenAI API 代理 - 完整接口保持
   * /proxy/openai/v1/chat/completions
   * /proxy/openai/v1/models
   * /proxy/openai/v1/embeddings
   */
  @Post('openai/v1/chat/completions')
  @ApiOperation({ summary: 'OpenAI Chat Completions API' })
  async openaiChatCompletions(@Body() request: any, @Headers() headers: any, @Req() req: Request) {
    return this.forwardRequest(ApiProvider.OPENAI, 'chat/completions', request, headers, req);
  }

  @Get('openai/v1/models')
  @ApiOperation({ summary: 'OpenAI Models API' })
  async openaiModels(@Headers() headers: any, @Req() req: Request) {
    return this.forwardRequest(ApiProvider.OPENAI, 'models', {}, headers, req);
  }

  @Post('openai/v1/embeddings')
  @ApiOperation({ summary: 'OpenAI Embeddings API' })
  async openaiEmbeddings(@Body() request: any, @Headers() headers: any, @Req() req: Request) {
    return this.forwardRequest(ApiProvider.OPENAI, 'embeddings', request, headers, req);
  }

  /**
   * Gemini API 代理 - 完整接口保持（示例）
   * /proxy/gemini/v1/generateContent
   * /proxy/gemini/v1/models
   */
  @Post('gemini/v1/generateContent')
  @ApiOperation({ summary: 'Gemini Generate Content API' })
  async geminiGenerateContent(@Body() request: any, @Headers() headers: any, @Req() req: Request) {
    // 检查是否支持 Gemini
    if (!this.adapterRegistry.isSupported(ApiProvider.GEMINI, TargetProvider.COPILOT)) {
      throw new BadRequestException('Gemini API not yet supported');
    }
    return this.forwardRequest(ApiProvider.GEMINI, 'generateContent', request, headers, req);
  }

  /**
   * 通用转发方法
   */
  private async forwardRequest(
    provider: ApiProvider,
    endpoint: string,
    request: any,
    headers: any,
    req: Request,
    query?: MessagesQueryDto
  ) {
    try {
      this.logger.log(`Forwarding ${provider} ${endpoint} request`);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        endpoint,
        query // Include query parameters in request info
      };
      
      // TODO: Process beta and extended headers in universal proxy forwarding
      if (query?.beta && provider === ApiProvider.ANTHROPIC) {
        // TODO: Handle beta parameter forwarding to Copilot
      }

      // 检查适配器是否可用
      if (!this.adapterRegistry.isSupported(provider, TargetProvider.COPILOT)) {
        throw new BadRequestException(`${provider} to Copilot forwarding not supported`);
      }

      // 转发请求
      const result = await this.enhancedForwarding.forwardApiRequest(
        provider,
        TargetProvider.COPILOT,
        request,
        requestInfo
      );

      return result;
    } catch (error) {
      this.logger.error(`Failed to forward ${provider} ${endpoint}: ${error.message}`);
      throw error;
    }
  }

  /**
   * 获取支持的 API 列表
   */
  @Get('supported-apis')
  @ApiOperation({ summary: 'Get Supported API Routes' })
  async getSupportedApis() {
    const routes = this.adapterRegistry.getSupportedRoutes();
    
    return {
      success: true,
      supportedRoutes: routes,
      endpoints: {
        anthropic: [
          'POST /proxy/anthropic/v1/messages',
          'POST /proxy/anthropic/v1/messages/count-tokens', 
          'GET /proxy/anthropic/v1/models'
        ],
        openai: [
          'POST /proxy/openai/v1/chat/completions',
          'POST /proxy/openai/v1/embeddings',
          'GET /proxy/openai/v1/models'
        ]
      }
    };
  }
}